package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.mapper.UserMapper;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import org.springframework.security.core.parameters.P;

@Service(interfaceClass = UserService.class)
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;



    @Override
    public User findByUsername(String username) {
        return userMapper.findByUsername(username);
    }

    @Override
    public PageResult findPage(Integer currentPage, Integer pageSize, String queryString) {
        //定义页面大小和当前页的页码
        PageHelper.startPage(currentPage,pageSize);
        //条件查询检查组信息
        List<User> list = userMapper.findByCondition(queryString);
        //包装数据
        PageInfo<User> pageInfo = new PageInfo<>(list);

        return new PageResult(pageInfo.getTotal(),pageInfo.getList());
    }

    @Override
    public void add(Integer[] roleIds, User user) {


        //新增数据插入到t_checkgroup
        userMapper.add(user);

        //新增t_checkgroup_checkitem数据
        setUserAndRole(roleIds,user.getId());
    }

    @Override
    public void edit(Integer[] roleIds, User user) {
        //通过检查组的id删除检查项
        userMapper.deleteAssociation(user.getId());
        //重新插入中间表数据
        setUserAndRole(roleIds,user.getId());
        //更新检查组数据
        userMapper.edit(user);
    }

    @Override
    public void deleteById(Integer id) {

        //删除检查组和检查项中间表数据
        userMapper.deleteAssociation(id);

        //删除检查组
        userMapper.deleteById(id);
    }

    private void setUserAndRole(Integer[] roleIds, Integer id) {

        if (roleIds!=null && roleIds.length>0){
            for (Integer roleId : roleIds) {
                userMapper.setUserAndRole(id,roleId);
            }

        }
    }
}
